package net.jxvtc.service.impl;
import java.math.BigDecimal;
import java.util.Arrays;
import java.util.List;


import com.alibaba.csp.sentinel.annotation.SentinelResource;
import com.fasterxml.jackson.databind.ObjectMapper;
import lombok.extern.slf4j.Slf4j;
import net.jxvtc.bean.Order;
import net.jxvtc.feign.ProductFeignClient;
import net.jxvtc.product.bean.Product;
import net.jxvtc.service.OrderService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.client.ServiceInstance;
import org.springframework.cloud.client.discovery.DiscoveryClient;
import org.springframework.cloud.client.loadbalancer.LoadBalancerClient;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;

@Slf4j
@Service
public class OrderServiceImpl implements OrderService {

    @Autowired
    RestTemplate restTemplate;

    @Autowired
    DiscoveryClient discoveryClient;

    @Autowired
    ProductFeignClient productFeign;

    @Autowired
    LoadBalancerClient loadBalancerClient;

    ObjectMapper mapper;

    @SentinelResource("createOrder")
    @Override
    public Order createOrder(Long userId, Long productId) {
        Product product =productFeign.getProduct(productId);
        Order order=new Order();
        order.setId(1L);
        order.setTotalAmount(product.getPrice().multiply(new BigDecimal(product.getNum())));
        order.setUserId(userId);
        order.setNickName("张三");
        order.setAddress("嘉兴职业技术学院");
        order.setProductList(Arrays.asList(product));


        return order;
    }


    private Product getProductFromRemoteWithOpenFeign(Long productId){

        Product product=productFeign.getProduct(productId);
        return product;
    }


    private Product getProductFromRemote(Long productId){
        List<ServiceInstance> instances = discoveryClient.getInstances("service-product");
        ServiceInstance instance = instances.get(0);
        String url="http://"+instance.getHost()+":"+instance.getPort()+"/product/"+productId;
        log.info(url);
        Product product=restTemplate.getForObject(url,Product.class);
        return product;
    }


    //进阶：完成负载均衡访问商品微服务
    private Product getProductFromRemoteWithLoadBalance(Long productId){

        ServiceInstance instance = loadBalancerClient.choose("service-product");
        String url="http://"+instance.getHost()+":"+instance.getPort()+"/product/"+productId;
        log.info(url);
        Product product=restTemplate.getForObject(url,Product.class);
        return product;
    }

    //进阶：完成负载均衡访问商品微服务
    private Product getProductFromRemoteWithLoadBalanceByAnnotation(Long productId){


        String url="http://service-product/product/"+productId;
        log.info(url);
        Product product=restTemplate.getForObject(url,Product.class);
        return product;
    }


}
